package com.wosiliujing.learning.mobile.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wosiliujing.learning.user.entity.SysUser;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.constant.LoginTypeConstants;
import com.wosiliujing.learning.constant.SecurityConstants;
import com.wosiliujing.learning.user.mapper.SysUserMapper;
import com.wosiliujing.learning.mobile.service.MobileService;
import com.wosiliujing.learning.util.RestResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 刘靖
 * @date 2019-09-26 14:37
 */
@Slf4j
@Service
@AllArgsConstructor
public class MobileServiceImpl implements MobileService {

    private final RedisTemplate redisTemplate;

    private final SysUserMapper userMapper;

    @Override
    public RestResult<String> sendSmsCode(String mobile) {
        SysUser sysUser = userMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone,mobile));
        if(ObjectUtil.isEmpty(sysUser)){
            log.info("手机号未注册{}:", mobile);
            return  RestResult.error("手机号未注册");
        }
        Object codeObject = redisTemplate.opsForValue().get(CommonConstants.SMS_CODE_KEY_ + LoginTypeConstants.SMS + "@" + mobile);
        if(ObjectUtil.isNotEmpty(codeObject)){
            log.info("验证码发送过于频繁:{} {}",mobile,codeObject);
            return RestResult.error("验证码发送过于频繁");
        }

        String code = RandomUtil.randomNumbers(SecurityConstants.CODE_SIZE);
        redisTemplate.opsForValue().set(CommonConstants.SMS_CODE_KEY_ + LoginTypeConstants.SMS + "@" + mobile,
                code, CommonConstants.CODE_TIME, TimeUnit.SECONDS);
        log.debug("生成验证码成功:{} {}",mobile ,code);
       return  RestResult.data(code);
    }
}
